package com.huiminpay.merchant.intercept;

import com.huiminpay.common.cache.exception.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.domain.ErrorCode;
import com.huiminpay.common.cache.domain.RestErrorResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: HWW
 * @Date: 2021/8/1917:19
 * @Desc: 全局异常处理器
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    //捕获Exception.class异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse processExcetion(HttpServletRequest request,
                                             HttpServletResponse response,Exception e){

        //解析异常信息

        //判断异常是自定义异常还是不可预知异常
        if(e instanceof BusinessException){
            log.error(e.getMessage(),e);
            //解析自定义异常
            BusinessException businessException = (BusinessException) e;
            ErrorCode errorCode = businessException.getErrorCode();
            //错误代码
            int code = errorCode.getCode();
            //错误信息
            String desc = errorCode.getDesc();

            return new RestErrorResponse(String.valueOf(code),desc);

        }

        //不可预知异常一律为：未知错误-999999
        log.error("系统异常",e);
        return new RestErrorResponse(String.valueOf(CommonErrorCode.UNKOWN.getCode()),CommonErrorCode.UNKOWN.getDesc());


    }
}
